using System;
using System.Collections.Concurrent;

namespace HEFramework
{
    /// <summary>
    ///
    /// 字节缓冲
    /// 
    /// ----------------------------------------
    /// 作者 hep
    /// 创建时间：2024-01-03 20:26:27
    /// ----------------------------------------
    /// </summary>
    public class Buffer
    {
        public static ConcurrentDictionary<int, ConcurrentStack<Buffer>> buffers = new();

        public static Buffer Get(int _size, bool _isClear = false)
        {
            Buffer buffer = null;
            ConcurrentStack<Buffer> stack = buffers.GetOrAdd(_size, _ => new ConcurrentStack<Buffer>());
            stack.TryPop(out buffer);
            if (buffer == null)
            {
                buffer = new Buffer(_size);
            }

            if (_isClear)
            {
                buffer.Clear();
            }

            return buffer;
        }

        public static void Put(Buffer _buff)
        {
            ConcurrentStack<Buffer> stack = buffers.GetOrAdd(_buff.Size, _ => new ConcurrentStack<Buffer>());
            stack.Push(_buff);
        }

        public byte[] Bytes { get; private set; }

        public int Size => Bytes.Length;

        public Buffer(int _size)
        {
            Bytes = new byte[_size];
        }

        public void Clear()
        {
            Array.Clear(Bytes, 0, Size);
        }
    }
}